package org.duiduo.common.feign.config;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.duiduo.common.feign.exceptions.FeignBadRequestException;
import org.springframework.http.HttpStatus;

import java.nio.charset.Charset;

/**
 * feign调用错误返回处理配置
 *
 * @author liangze
 * @date 2024/10/12 10:59
 */
@Slf4j
public class FeignErrorConfig implements ErrorDecoder {

    @Override
    public Exception decode(String methodKey, Response response) {
        if (response.status() != HttpStatus.OK.value()) {
            if (response.status() == HttpStatus.INTERNAL_SERVER_ERROR.value() || response.status() == HttpStatus.BAD_REQUEST.value()) {
                FeignBadRequestException badRequestException = new FeignBadRequestException("请求异常");
                try {
                    String errorContent = Util.toString(response.body().asReader(Charset.defaultCharset()));
                    log.info("errorContent====> {}", errorContent);
                    if (StrUtil.isNotBlank(errorContent)) {
                        errorContent = errorContent.replaceAll("\t", "").replaceAll("\n", "");
                    }
                    JSONObject jsonObject = JSON.parseObject(errorContent);
                    if (null != jsonObject) {
                        String msg = jsonObject.getString("message");
                        if (StrUtil.isNotBlank(msg)) {
                            badRequestException = new FeignBadRequestException(msg);
                        }
                    }
                } catch (Exception e) {
                    log.error("Exception: ", e);
                }
                return badRequestException;
            }
        }
        return new FeignBadRequestException("未知异常");
    }

}
